package com.maiyawx.mall.controller;

import com.alibaba.fastjson.JSONObject;
import com.maiyawx.mall.entity.RequestLogin;
import com.maiyawx.mall.entity.Result;
import com.maiyawx.mall.entity.Users;
import com.maiyawx.mall.enums.CommonEnum;
import com.maiyawx.mall.exception.CommonException;
import com.maiyawx.mall.service.AccountsService;
import com.maiyawx.mall.service.BlacklistService;
import com.maiyawx.mall.service.UsersService;
import com.maiyawx.mall.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户
 */
@RestController()
public class UsersController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private AccountsService accountsService;

    @Autowired
    private BlacklistService blacklistService;

    @PostMapping(value = "users",produces = "application/json;charset=UTF-8")

    /**
     * 用户登录
     */
    public Result login(
            HttpServletRequest request,
            @RequestBody @Valid RequestLogin requestLogin, Errors errors) {
        //判断参数验证
        if (errors.hasErrors()){
            return ResultUtil.error(CommonEnum.VALID_ERROR.getCode(), errors.getFieldError().getDefaultMessage());
        }
        //获取秘钥
        String secret = accountsService.selectSecret(requestLogin.getAppid());
        //拼接接口地址
        String sessionKeyUrl = UserInfoUtil.getSessionKey(requestLogin.getAppid(), secret, requestLogin.getCode());
        //调用微信接口
        JSONObject sessionKeyData = WxHttpsUtil.get(sessionKeyUrl);
        //解密微信用户信息
        JSONObject userInfo = WXUtil.getUserInfo(requestLogin.getEncryptedData(), sessionKeyData.getString("session_key"), requestLogin.getIv());
        if (userInfo!= null) {
            //添加用户或更新用户信息
            Users users = usersService.addOrUpdate(userInfo, sessionKeyData, request);
            //获取黑名单信息
            Boolean hasUser = blacklistService.hasUser(requestLogin.getAppid(), users.getId());
            if (hasUser) {
                //在黑名单中返回错误
                return ResultUtil.error(CommonEnum.SERVER_ERROR);
            }
            //拼接返回结构体
            Map<String, Object> resultData = new HashMap<String, Object>();
            //jtw 令牌
            resultData.put("token", JWTUtil.createToken(users));
            //jwt 有效期
            resultData.put("expires", JWTUtil.getExpireDate().getTime());
            resultData.put("uid", users.getId());
//            resultData.putAll(JSONObject.parseObject(JSONObject.toJSONString(users), Map.class));
            return ResultUtil.success(resultData);
        } else {
            throw new CommonException(CommonEnum.DECODE_USERINFO_ERROR);
        }
    }
}
